<template>
  <div class="persona-selector">
    <!-- 当前人格显示 -->
    <div class="current-persona" @click="toggleSelector">
      <div class="persona-avatar">
        <img
          v-if="currentPersona?.avatar"
          :src="currentPersona.avatar"
          :alt="currentPersona.name"
          class="avatar-image"
        />
        <Icon v-else name="user" :size="24" class="avatar-icon" />
      </div>

      <div class="persona-info">
        <div class="persona-name">{{ currentPersona?.name || "选择人格" }}</div>
        <div v-if="currentPersona?.description" class="persona-description">
          {{ currentPersona.description }}
        </div>
      </div>

      <Icon
        name="chevron-down"
        :size="16"
        class="expand-icon"
        :class="{ expanded: showSelector }"
      />
    </div>

    <!-- 人格选择器 -->
    <div v-if="showSelector" class="persona-dropdown">
      <!-- 搜索框 -->
      <div class="search-section">
        <Input
          v-model="searchQuery"
          placeholder="搜索人格..."
          size="small"
          prefix-icon="search"
          clearable
        />
      </div>

      <!-- 人格分类 -->
      <div class="category-tabs">
        <button
          v-for="category in categories"
          :key="category.key"
          class="category-tab"
          :class="{ active: selectedCategory === category.key }"
          @click="selectCategory(category.key)"
        >
          <Icon :name="category.icon" :size="16" />
          <span>{{ category.name }}</span>
          <span class="category-count"
            >({{ getCategoryCount(category.key) }})</span
          >
        </button>
      </div>

      <!-- 人格列表 -->
      <div class="persona-list">
        <div
          v-for="persona in filteredPersonas"
          :key="persona.id"
          class="persona-item"
          :class="{
            active: currentPersona?.id === persona.id,
            disabled: !persona.enabled,
          }"
          @click="selectPersona(persona)"
        >
          <div class="persona-avatar-small">
            <img
              v-if="persona.avatar"
              :src="persona.avatar"
              :alt="persona.name"
              class="avatar-image-small"
            />
            <Icon v-else name="user" :size="20" class="avatar-icon-small" />
          </div>

          <div class="persona-details">
            <div class="persona-header">
              <span class="persona-name-small">{{ persona.name }}</span>
              <div class="persona-badges">
                <span v-if="persona.isDefault" class="badge badge-default"
                  >默认</span
                >
                <span v-if="persona.isPremium" class="badge badge-premium"
                  >高级</span
                >
                <span v-if="!persona.enabled" class="badge badge-disabled"
                  >禁用</span
                >
              </div>
            </div>

            <div class="persona-description-small">
              {{ persona.description }}
            </div>

            <div class="persona-meta">
              <div class="persona-tags">
                <span
                  v-for="tag in persona.tags?.slice(0, 3)"
                  :key="tag"
                  class="persona-tag"
                >
                  {{ tag }}
                </span>
              </div>

              <div class="persona-stats">
                <span class="stat-item">
                  <Icon name="message-circle" :size="12" />
                  {{ persona.messageCount || 0 }}
                </span>
                <span class="stat-item">
                  <Icon name="star" :size="12" />
                  {{ persona.rating || 0 }}
                </span>
              </div>
            </div>
          </div>

          <div class="persona-actions">
            <Button
              v-if="persona.id !== currentPersona?.id"
              type="primary"
              size="small"
              @click.stop="selectPersona(persona)"
            >
              选择
            </Button>

            <Button
              type="secondary"
              variant="text"
              icon="settings"
              size="small"
              @click.stop="editPersona(persona)"
              title="编辑"
            />

            <Button
              v-if="!persona.isDefault"
              type="danger"
              variant="text"
              icon="trash"
              size="small"
              @click.stop="deletePersona(persona)"
              title="删除"
            />
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredPersonas.length === 0" class="empty-state">
          <Icon name="search" :size="48" class="empty-icon" />
          <div class="empty-text">未找到匹配的人格</div>
          <div class="empty-description">尝试调整搜索条件或创建新的人格</div>
        </div>
      </div>

      <!-- 底部操作 -->
      <div class="selector-footer">
        <Button
          type="primary"
          icon="plus"
          @click="createPersona"
          class="create-btn"
        >
          创建新人格
        </Button>

        <Button
          type="secondary"
          variant="text"
          icon="settings"
          @click="openPersonaManager"
          title="人格管理"
        />
      </div>
    </div>

    <!-- 遮罩层 -->
    <div
      v-if="showSelector"
      class="selector-overlay"
      @click="closeSelector"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { usePersonaStore } from "@/stores/persona";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Input from "@/components/common/Input.vue";

interface Persona {
  id: string;
  name: string;
  description: string;
  avatar?: string;
  category: string;
  tags?: string[];
  enabled: boolean;
  isDefault?: boolean;
  isPremium?: boolean;
  messageCount?: number;
  rating?: number;
  parameters?: Record<string, any>;
}

interface Props {
  size?: "small" | "medium" | "large";
  showDescription?: boolean;
  maxHeight?: string;
}

const props = withDefaults(defineProps<Props>(), {
  size: "medium",
  showDescription: true,
  maxHeight: "400px",
});

const emit = defineEmits<{
  select: [persona: Persona];
  create: [];
  edit: [persona: Persona];
  delete: [persona: Persona];
  manage: [];
}>();

// Store
const personaStore = usePersonaStore();

// 响应式数据
const showSelector = ref(false);
const searchQuery = ref("");
const selectedCategory = ref("all");

// 计算属性
const currentPersona = computed(() => personaStore.currentPersona);
const personas = computed(() => personaStore.personas);

// 人格分类
const categories = [
  { key: "all", name: "全部", icon: "grid" },
  { key: "assistant", name: "助手", icon: "bot" },
  { key: "companion", name: "陪伴", icon: "heart" },
  { key: "professional", name: "专业", icon: "briefcase" },
  { key: "creative", name: "创意", icon: "palette" },
  { key: "entertainment", name: "娱乐", icon: "smile" },
  { key: "custom", name: "自定义", icon: "user" },
];

// 过滤后的人格列表
const filteredPersonas = computed(() => {
  let filtered = personas.value;

  // 按分类过滤
  if (selectedCategory.value !== "all") {
    filtered = filtered.filter(
      (persona) => persona.category === selectedCategory.value,
    );
  }

  // 按搜索关键词过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim();
    filtered = filtered.filter(
      (persona) =>
        persona.name.toLowerCase().includes(query) ||
        persona.description.toLowerCase().includes(query) ||
        persona.tags?.some((tag) => tag.toLowerCase().includes(query)),
    );
  }

  // 排序：当前选中的在前，然后按使用次数排序
  return filtered.sort((a, b) => {
    if (a.id === currentPersona.value?.id) return -1;
    if (b.id === currentPersona.value?.id) return 1;
    return (b.messageCount || 0) - (a.messageCount || 0);
  });
});

// 方法
const toggleSelector = () => {
  showSelector.value = !showSelector.value;
};

const closeSelector = () => {
  showSelector.value = false;
};

const selectCategory = (category: string) => {
  selectedCategory.value = category;
};

const getCategoryCount = (category: string): number => {
  if (category === "all") return personas.value.length;
  return personas.value.filter((persona) => persona.category === category)
    .length;
};

const selectPersona = async (persona: Persona) => {
  if (!persona.enabled) return;

  try {
    await personaStore.switchPersona(persona.id);
    emit("select", persona);
    closeSelector();
  } catch (error) {
    // 切换人格失败
  }
};

const createPersona = () => {
  emit("create");
  closeSelector();
};

const editPersona = (persona: Persona) => {
  emit("edit", persona);
  closeSelector();
};

const deletePersona = (persona: Persona) => {
  if (confirm(`确定要删除人格 "${persona.name}" 吗？`)) {
    emit("delete", persona);
  }
};

const openPersonaManager = () => {
  emit("manage");
  closeSelector();
};

// 生命周期
onMounted(() => {
  // 加载人格列表
  personaStore.loadPersonas();

  // 点击外部关闭
  document.addEventListener("click", handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});

const handleClickOutside = (event: Event) => {
  const target = event.target as Element;
  if (!target.closest(".persona-selector")) {
    closeSelector();
  }
};
</script>

<style scoped>
/* 人格选择器基础样式 */
.persona-selector {
  position: relative;
  display: inline-block;
}

/* 当前人格显示 */
.current-persona {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 200px;
}

.current-persona:hover {
  background-color: var(--bg-tertiary);
  border-color: var(--primary-color);
}

.persona-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-icon {
  color: var(--text-tertiary);
}

.persona-info {
  flex: 1;
  min-width: 0;
}

.persona-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.persona-description {
  font-size: 12px;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 2px;
}

.expand-icon {
  color: var(--text-tertiary);
  transition: transform 0.2s ease;
  flex-shrink: 0;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

/* 人格下拉选择器 */
.persona-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  box-shadow: var(--shadow-lg);
  z-index: 1000;
  margin-top: 4px;
  max-height: v-bind(maxHeight);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 搜索区域 */
.search-section {
  padding: 12px;
  border-bottom: 1px solid var(--border-color);
}

/* 分类标签 */
.category-tabs {
  display: flex;
  padding: 8px;
  gap: 4px;
  border-bottom: 1px solid var(--border-color);
  overflow-x: auto;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: none;
  background: transparent;
  border-radius: 6px;
  font-size: 12px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  flex-shrink: 0;
}

.category-tab:hover {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
}

.category-tab.active {
  background-color: var(--primary-color);
  color: white;
}

.category-count {
  font-size: 10px;
  opacity: 0.8;
}

/* 人格列表 */
.persona-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.persona-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 4px;
}

.persona-item:hover {
  background-color: var(--bg-secondary);
}

.persona-item.active {
  background-color: var(--primary-color-light);
  border: 1px solid var(--primary-color);
}

.persona-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.persona-item.disabled:hover {
  background-color: transparent;
}

/* 小头像 */
.persona-avatar-small {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-image-small {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-icon-small {
  color: var(--text-tertiary);
}

/* 人格详情 */
.persona-details {
  flex: 1;
  min-width: 0;
}

.persona-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.persona-name-small {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.persona-badges {
  display: flex;
  gap: 4px;
}

.badge {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
  text-transform: uppercase;
}

.badge-default {
  background-color: var(--success-color-light);
  color: var(--success-color);
}

.badge-premium {
  background-color: var(--warning-color-light);
  color: var(--warning-color);
}

.badge-disabled {
  background-color: var(--error-color-light);
  color: var(--error-color);
}

.persona-description-small {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.persona-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.persona-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.persona-tag {
  padding: 2px 6px;
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
  border-radius: 4px;
  font-size: 10px;
}

.persona-stats {
  display: flex;
  gap: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 10px;
  color: var(--text-tertiary);
}

/* 人格操作 */
.persona-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.persona-item:hover .persona-actions {
  opacity: 1;
}

.persona-item.active .persona-actions {
  opacity: 1;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  color: var(--text-tertiary);
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.empty-description {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 底部操作 */
.selector-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-top: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

.create-btn {
  flex: 1;
  margin-right: 8px;
}

/* 遮罩层 */
.selector-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 尺寸变体 */
.persona-selector.size-small .current-persona {
  padding: 6px 8px;
  min-width: 150px;
}

.persona-selector.size-small .persona-avatar {
  width: 24px;
  height: 24px;
}

.persona-selector.size-small .persona-name {
  font-size: 12px;
}

.persona-selector.size-large .current-persona {
  padding: 12px 16px;
  min-width: 250px;
}

.persona-selector.size-large .persona-avatar {
  width: 40px;
  height: 40px;
}

.persona-selector.size-large .persona-name {
  font-size: 16px;
}

/* 响应式 */
@media (max-width: 768px) {
  .persona-dropdown {
    left: -50%;
    right: -50%;
    min-width: 300px;
  }

  .category-tabs {
    padding: 6px;
  }

  .category-tab {
    padding: 4px 8px;
    font-size: 11px;
  }

  .persona-item {
    padding: 8px;
  }

  .persona-avatar-small {
    width: 32px;
    height: 32px;
  }

  .persona-actions {
    opacity: 1; /* 移动端始终显示 */
  }
}

@media (max-width: 480px) {
  .current-persona {
    min-width: 120px;
    padding: 6px 8px;
  }

  .persona-avatar {
    width: 24px;
    height: 24px;
  }

  .persona-name {
    font-size: 12px;
  }

  .persona-description {
    display: none;
  }

  .persona-dropdown {
    left: -100%;
    right: -100%;
    min-width: 280px;
  }
}

/* 滚动条样式 */
.category-tabs::-webkit-scrollbar,
.persona-list::-webkit-scrollbar {
  height: 4px;
  width: 6px;
}

.category-tabs::-webkit-scrollbar-track,
.persona-list::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 2px;
}

.category-tabs::-webkit-scrollbar-thumb,
.persona-list::-webkit-scrollbar-thumb {
  background: var(--text-tertiary);
  border-radius: 2px;
}

.category-tabs::-webkit-scrollbar-thumb:hover,
.persona-list::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}

/* 无障碍支持 */
@media (prefers-reduced-motion: reduce) {
  .expand-icon,
  .persona-item,
  .category-tab,
  .current-persona {
    transition: none;
  }
}
</style>
